package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.area.model.entity.Area;
import com.wing.area.model.response.AreaVO;
import com.wing.area.service.AreaService;
import com.wing.common.enums.OperationLogDesc;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.Product;
import com.wing.product.model.entity.ProductBrand;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.request.CustomersInfoForm;
import com.wing.sell.model.response.AgentVO;
import com.wing.sell.model.response.CustomersInfoVO;
import com.wing.sell.service.*;
import com.wing.user.feign.UserClient;
import com.wing.user.model.request.User;
import com.wing.user.model.response.UserVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.excel.CustomerExcelIn;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.ProductExcelIn;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author
 */
@Slf4j
@Validated
@Api(value = "Admin-客户信息管理", tags = "#/sell/customersInfo")
@RestController("customersInfoController")
@RequestMapping("sell/admin/customersInfo")
@RequiredArgsConstructor
public class CustomersInfoController {

    private final CustomersInfoService customersInfoService;
    private final AgentCategoryService agentCategoryService;
    private final AgentLevelService agentLevelService;

    @Resource
    UserClient userClient;

    @ApiOperation(value = "查询所有正式客户信息", notes = "搜索")
    @GetMapping("/list")
    public PageResult<CustomersInfoVO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String customerName, String licenseNo, String id) {

        Page<CustomersInfoVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", StrUtil.toUnderlineCase(sort));
            params.put("order", order);
        }

//        Long companyInfoId = JwtUtils.getEnterpriseId();
        params.put("customerName", customerName);
        params.put("licenseNo", licenseNo);
        params.put("id", id);
//        params.put("companyInfoId", companyInfoId);
        params.put("customerType", 3);

        IPage<CustomersInfoVO> list = customersInfoService.pageList4app(pg, params);
        //关联相关业务属性
        list.getRecords().parallelStream().forEach(k -> {
            //分类名称
            AgentCategory agentCategory = agentCategoryService.getById(k.getAgentCategoryId());
            if (null != agentCategory) {
                k.setAgentCategoryName(agentCategory.getName());
            }
            //代理级别名称
            AgentLevel agentLevel = agentLevelService.getById(k.getAgtLevel());
            if (null != agentLevel) {
                k.setAgtLevelName(agentLevel.getName());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询客户基本信息(主要用于下拉框查询客户)", notes = "搜索")
    @GetMapping("/getBasicInfo")
    public JsonResult<CustomersInfo> getBasicInfo(String customerType,String userId) {
        QueryWrapper<CustomersInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(customerType)) {
            queryWrapper.in("customer_type", Arrays.asList(customerType.split(",")));
        }
        if (StringUtils.isNotBlank(userId)) {
            queryWrapper.in("id", Arrays.asList(userId.split(",")));
        }
        List<CustomersInfo> list = customersInfoService.list(queryWrapper);
        if (list.isEmpty()) {
            return JsonResult.fail("未查询到客户信息");
        }
        return JsonResult.success(list);
    }


    @ApiOperation(value = "添加客户信息", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    @OperationLogDesc(module = "添加客户信息", events = "添加>正式客户")
    public JsonResult add(@Validated(CustomersInfoForm.Add.class) CustomersInfoForm customersInfoForm) {
        //查询是否有同名的
        QueryWrapper<CustomersInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_name", customersInfoForm.getCustomerName());
        CustomersInfo one = this.customersInfoService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(one)) {
            return JsonResult.fail("此公司名已被使用！");
        }
        if (customersInfoService.add(customersInfoForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改客户信息", notes = "修改")
    @PutMapping("/update")
    @OperationLogDesc(module = "修改客户信息", events = "修改>正式客户")
    public JsonResult update(@Validated(CustomersInfoForm.Update.class) CustomersInfoForm customersInfoForm) {
        CustomersInfo customersInfo = customersInfoService.getById(customersInfoForm.getId());
        if (customersInfo == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(CustomersInfo.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(customersInfoForm, customersInfo, copyOptions);
        if (customersInfoService.updateById(customersInfo)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除客户信息", notes = "删除")
    @DeleteMapping("/{id}")
    @OperationLogDesc(module = "删除客户信息", events = "删除>正式客户")
    public JsonResult delete(@PathVariable("id") Long customersInfoId) {
        CustomersInfo customersInfo = customersInfoService.getById(customersInfoId);
        if (customersInfoService.removeById(customersInfoId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    @GetMapping("/getCustomerByType")
    public JsonResult getCustomerByType(String customerTypeName) {
        int customerType = 0;
        Map<String, Object> params = new HashMap<>();

        if (StringUtils.isNotBlank(customerTypeName)) {
            if ("potential".equals(customerTypeName)) {
                customerType = CustomerFollowRecord.CustomerType.potential.getValue();
            } else if ("Intended".equals(customerTypeName)) {
                customerType = CustomerFollowRecord.CustomerType.Intended.getValue();
            } else {
                customerType = CustomerFollowRecord.CustomerType.formal.getValue();
            }
            params.put("customerType", customerType);
        }

        List<CustomersInfoVO> list = customersInfoService.list4app(params);
        if (list.isEmpty()) {
            log.info("数据为空：" + list);
            return JsonResult.fail("该客户类型下未查询到客户");
        }
        return JsonResult.success(list);
    }

    @GetMapping("/getLeadList")
    public JsonResult getLeadList(Long id) {

        List<CustomersInfoVO> list = customersInfoService.leadList(id);

        if (list.isEmpty()) {
            log.info("数据为空！" + list);
            return JsonResult.fail("未查到数据");
        }
        return JsonResult.success(list);
    }

    @PutMapping("/updateSalesman")
    public JsonResult updateSalesman(Long id, Long salesmanId) {
        if (id == 0 || id == null) {
            return JsonResult.fail("客户ID为" + id);
        }
        CustomersInfo customersInfo = new CustomersInfo();
        customersInfo.setId(id);
        customersInfo.setSalesmanId(salesmanId);
        if (customersInfoService.updateById(customersInfo)) {
            return JsonResult.success();
        }
        return JsonResult.fail();
    }

    /**
     * 下载产品数据录入excel模板
     */
    @ApiOperation(value = "下载产品数据录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"客户编码","客户类型", "客户名称", "营业执照号", "省/市/区", "详情地址", "联系人姓名", "所属部门", "电话", "微信", "邮箱", "审批人", "所属代理商", "业务员", "职务", "线索来源", "推荐人", "年用刀量"};
        String[] indexArr = {"1", "11", "12", "13", "14", "15"};

        customersInfoService.templetDown(response, request, headerArr, indexArr);
    }

    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    @OperationLogDesc(module = "导入正式客户excel", events = "导入>正式客户")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("上传文件为空！");
        }
        try {
            //获取原始的文件名
            ExcelUtil<CustomerExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<CustomerExcelIn> list = reader.read(is, CustomerExcelIn.class);

            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }

            return customersInfoService.importFile(list);

        } catch (Exception e) {
            log.error("上传文件异常！异常信息:", e);
            return JsonResult.exception("上传文件异常！异常信息:" + e.getMessage());
        }
    }

}
